package com.ews.onlineexchange.controller;

import javax.enterprise.context.ConversationScoped;
import javax.enterprise.event.Event;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.RejectRecord;
import com.ews.onlineexchange.model.ServiceBuyer;
import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.BlackListService;
import com.ews.onlineexchange.service.EntityHome;
import com.ews.onlineexchange.service.RejectRecordHome;
import com.ews.onlineexchange.service.UserSeqNoGenerator;
import com.ews.onlineexchange.service.UserService;
import com.ews.onlineexchange.service.qualifier.ServiceBuyerRejectEvent;
import com.ews.onlineexchange.util.AesUtil;
import com.ews.onlineexchange.util.SerialnumberUtil;

@Named
@ConversationScoped
public class ServiceBuyerHome extends EntityHome<ServiceBuyer, String> {

	@Inject
	UserSeqNoGenerator			userSeqNoGenerator;
	@Inject
	EntityManager				entityManager;
	private static final long	serialVersionUID	= 1L;
	private String				confirmPassword;
	private RejectRecord		rejectRecord;

	private boolean				self;
	
	@Override
	public String getId() {
		if ( isSelf() ) {
			this.setId( userService.getLoginedUser().getId() );
		}
		return super.getId();
	}
	
	public String getConfirmPassword() {
		return confirmPassword;
	}
	
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}
	/**
	 * 暂时废弃 先不删  和前台  validator 属性组合使用
	 * @param context
	 * @param componentToValidate
	 * @param value
	 * @throws ValidatorException
	 */
	public void validateUsernameExist(FacesContext context,
              UIComponent componentToValidate,Object value)throws ValidatorException {
				if (this.isUsernameExist(value+"")) {
				FacesMessage message =new FacesMessage("用户名已存在！");
				 message.setSeverity(FacesMessage.SEVERITY_ERROR);
				throw new ValidatorException(message);
			
			}
				
	}
	public void validateEmailExist(FacesContext context,
            UIComponent componentToValidate,Object value)throws ValidatorException {
				if (this.isEmailExist(value+"")) {
				FacesMessage message =new FacesMessage("邮箱已存在已存在！");
				 message.setSeverity(FacesMessage.SEVERITY_ERROR);
				throw new ValidatorException(message);
			
			}
				
	}
	
	/**验证登录名是否存在
	 * @param username
	 * @return
	 */
	public boolean isUsernameExist(String username) {
		boolean flag = true;
		StringBuffer sql = new StringBuffer( "SELECT count(*) FROM ServiceBuyer b where b.username=? and delflag != '0'");
		long count = (long)getEntityManager().createQuery(sql.toString()).setParameter(1, username).getSingleResult();
		if(count == 0) flag =false;
		
		return flag;
		
	}
	/**
	 * 验证邮箱是否存在
	 * @param email
	 * @return
	 */
	public boolean isEmailExist(String email) {
		boolean flag = true;
		StringBuffer sql = new StringBuffer( "SELECT count(*) FROM ServiceBuyer b where b.email=? and delflag != '0'");
		long count = (long)getEntityManager().createQuery(sql.toString()).setParameter(1, email).getSingleResult();
		if(count == 0) flag =false;
		
		return flag;
		
	}
	
	
	@Inject
	BlackListService blackListService;
	@Override
	public String saveAndFlush() {
		boolean managed = isManaged();
		String creditCode = getInstance().getCreditCode();
		if(!SerialnumberUtil.isRightSerialnumber(creditCode)){
			FacesContext.getCurrentInstance().addMessage("creditCode",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "统一社会信用代码格式有误，请检查！", ""));
			return null;
		}
		if(!managed){
			getInstance().setSeqNo(userSeqNoGenerator.getNextSeqNo());
			getInstance().setRoles("buyer");
			getInstance().setShiroPwd(userService.entryptPassword(getInstance().getPassword()));
		}
		String result =  super.saveAndFlush();
		
		if (!managed && result.equals(RESULT_SAVED)) {
			return result;
		}
		
		if (result.equals(RESULT_SAVED)) {
			return result;
		}
		
		return null;
	}
	
	public String saveEditInfo() {
		String result =  super.saveAndFlush();
		if (result.equals(RESULT_SAVED))  return "/business/buyer/unitInfo.xhtml";
		else return null;
	}
	
	@Inject
	UserService userService;
	public String reSubmit() {
		//当重新提交审核，重新查询一下用户，查询最新的auditted
		//由于loginedUser 只是加载一次的，故当重新提交后，重新更新一下当前登录用户，可 使审核失败的菜单隐藏
//		String username = keycloakUserService.findLoginedUsername();
		User user = userService.findLoginedUser();
		user.setAuditted(null);
		userService.setLoginedUser(user);
		getInstance().setAuditted(null);
		return super.saveAndFlush();
} 
	
	@Override
	public String delete() {
		getInstance().setDelFlag(DataEntity.DEL_FLAG_DELETE);
		String result = super.saveAndFlush();
		if (result.equals(RESULT_SAVED)) {
			return RESULT_DELETED;
		}
		return null;
	}
	
	public String audit() {
		getInstance().setAuditted(true);
		String result = super.saveAndFlush();
		if (result.equals(RESULT_SAVED)) {
			return "auditted";
		}
		return null;
	}
	
	@Inject
	RejectRecordHome rejectRecordHome;
	@Inject
	@ServiceBuyerRejectEvent
	Event<ServiceBuyer> serviceBuyerRejectEvent;
	public String reject() {
		getInstance().setAuditted(false);		
		RejectRecord rejectRecord = rejectRecordHome.getInstance();
		getInstance().setCurrRejectRecord(rejectRecord);
		getInstance().getHistoryRejectRecords().add(rejectRecord);
		String result = save();
		if (result.equals("saved")) {
			super.flush();
			serviceBuyerRejectEvent.fire(getInstance());
			return "rejected";
		}
			
		return null;
	}

	public RejectRecord getRejectRecord() {
		return rejectRecord;
	}

	public void setRejectRecord(RejectRecord rejectRecord) {
		this.rejectRecord = rejectRecord;
	}

	public boolean isSelf() {
		return self;
	}

	public void setSelf( boolean self ) {
		this.self = self;
	}
	
	
}
